package com.guo.erp;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.stream.JsonReader;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ContactManger {
	private static final String CONTACT_URL = "http://10.2.11.40/restepmservice/read/contactlist";
	private static ArrayList<Contact> list = new ArrayList<Contact>();
	private OpenSQLite sqLite;
	private SQLiteDatabase database;
	int count;
	String timestamp;
	static boolean isdownload = false;

	public ContactManger(Context context) {
		sqLite = new OpenSQLite(context);
		database = sqLite.getWritableDatabase();
	}

	public static ArrayList<Contact> getList() {
		return list;
	}

	private boolean parseContact_message(String contact_message) {
		String contact_message1 = null;
		try {
			JSONObject jsonObject = new JSONObject(contact_message);
			contact_message1 = jsonObject.get("contacts").toString();
		} catch (JSONException e) {

			e.printStackTrace();
		}
		JsonReader jsonReader = new JsonReader(new StringReader(
				contact_message1));
		try {
			jsonReader.beginArray();
			while (jsonReader.hasNext()) {
				jsonReader.beginObject();
				Contact contact = new Contact();
				while (jsonReader.hasNext()) {

					String name = jsonReader.nextName();

					if (name.toString().equalsIgnoreCase("GroupName")) {
						contact.mSubDept = jsonReader.nextString();
					} else if (name.equalsIgnoreCase("UserName")) {
						contact.mName = jsonReader.nextString();
					} else if (name.equalsIgnoreCase("MobilePhone")) {
						contact.mNum = jsonReader.nextString();
					} else if (name.equalsIgnoreCase("DepartmentName")) {
						contact.mDept = jsonReader.nextString();
					} else if (name.equalsIgnoreCase("Position")) {
						contact.mDusty = jsonReader.nextString();
					}

				}
				jsonReader.endObject();
				list.add(contact);
			}
			jsonReader.endArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;

	}

	private boolean parseControl_message(String control_message) {
		String string = control_message;
		String[] strings = string.split(",");
		if ("0000".equals(strings[2].substring(strings[2].indexOf(":") + 2,
				strings[2].indexOf(":") + 8))) {
			count = Integer.parseInt(strings[1].substring(strings[1]
					.indexOf(':') + 1));
			timestamp = strings[3].substring(strings[3].indexOf(':') + 2,
					strings[3].lastIndexOf('"'));
		} else {
			return false;
		}
		return true;
	}

	public boolean download() {
		String url1 = CONTACT_URL + "?userId=" + LoginActivity.getUserName()
				+ "&password=" + LoginActivity.getPassWord()
				+ "&start=&end=&Timestamp=";
		String Control_message = LoginActivity.getGetResponse(url1);
		if (!parseControl_message(Control_message)) {
			return false;
		}
		String url2 = CONTACT_URL + "?userId=" + LoginActivity.getUserName()
				+ "&password=" + LoginActivity.getPassWord() + "&start=0&end="
				+ count + "&Timestamp=";
		String Contact_message = LoginActivity.getGetResponse(url2);
		if (!parseContact_message(Contact_message)) {
			return false;
		}
		Iterator<Contact> iterator = list.iterator();
		while (iterator.hasNext()) {
			add(iterator.next());
		}
		isdownload = true;
		return true;

	}

	private boolean add(Contact contact) {
		if (isdownload) {
			return false;
		}
		database.beginTransaction();
		ContentValues values = new ContentValues();
		values.put("name", contact.mName);
		values.put("dept", contact.mDept);
		values.put("subdept", contact.mSubDept);
		values.put("phone_no", contact.mNum);
		values.put("position", contact.mDusty);
		database.insert("contacts", null, values);
		database.setTransactionSuccessful();
		database.endTransaction();
		return true;
	}

	public boolean del(int now_position) {
		if (isdownload) {
			return false;
		}
		database.beginTransaction();
		database.delete("contacts", "id = ? ", new String[] { "23" });
		database.setTransactionSuccessful();
		database.endTransaction();
		return true;
	}

	public boolean update(int now_position, Contact contact) {
		if (isdownload) {
			return false;
		}
		;
		del(now_position);
		add(contact);
		return true;
	}

	public ArrayList<Contact> query() {
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		database.beginTransaction();
		Cursor cursor = database.query("contacts", new String[] { "name",
				"dept", "subdept", "telephone", "IsActive", "GroupId",
				"DepartmentId", "UserId", "Position" }, null, null, null, null,
				null);
		cursor.moveToFirst();
		while (cursor.moveToNext()) {
			Contact contact = new Contact();
			contact.mName = cursor.getString(cursor.getColumnIndex("name"));
			contact.mDept = cursor.getString(cursor.getColumnIndex("dept"));
			contact.mSubDept = cursor.getString(cursor
					.getColumnIndex("subdept"));
			contact.mNum = cursor.getString(cursor.getColumnIndex("telephone"));
			contact.mDusty = cursor
					.getString(cursor.getColumnIndex("Position"));
			contacts.add(contact);
		}
		database.setTransactionSuccessful();
		database.endTransaction();
		return contacts;

	}
}
